﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;

namespace testClient
{
	class MainClass
	{
		
		private static TcpClient client;

		private static byte[] buffer = new byte[1024];

		private static async void RecvAsync()
		{
			var stream = client.GetStream();
			while (true)
			{
				var n = 0;
				try
				{
					n = await stream.ReadAsync(buffer, 0, 1024);
				}
				catch (Exception exp)
				{
					Console.WriteLine(exp.ToString());
					return;
				}
				if (n == 0)
				{
					return;
				}
				else {
					var retStr = Encoding.ASCII.GetString(buffer, 0, n);
					Console.WriteLine("Receive: " + retStr);
				}

			}

		}




		static void Connect()
		{
			//socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
			Console.WriteLine("BeforeConnect");

			try
			{
				client = new TcpClient("127.0.0.1", 4040);
			}
			catch (Exception exp)
			{
				Console.WriteLine("ConnectFail: "+exp.ToString());
				return;
			}

			RecvAsync();

			Send();

		}

		static void Send()
		{
			while (true)
			{
				var ret = Input();
				if (ret == "close")
				{
					return;
				}
			}
		}

		static void SendByte(string s)
		{
			Console.WriteLine("BeforeReceive");
			var bytes = Encoding.ASCII.GetBytes(s);
			var n = 0;
			var stream = client.GetStream();

			try
			{
				//n = socket.Send(bytes);
				stream.Write(bytes, 0, bytes.Length);
			}
			catch (Exception exp)
			{
				Console.WriteLine(exp.ToString());
				return;
			}

		}

		static void Close()
		{
			client.Close();
			client = null;
		}

		static string Input()
		{
			Console.WriteLine("Please Input:");
			var line = Console.ReadLine();
			var cmds = line.Split(char.Parse(" "));
			var c = cmds[0];
			//c
			//s helloworld
			//close 
			if (c == "c")
			{
				Connect();
			}
			else if (c == "s")
			{
				SendByte(cmds[1]);
			}
			else if (c == "close")
			{
				Close();
			}
			return c;
		}

		public static void Main(string[] args)
		{
			while (true)
			{
				var cmd = Input();
				if (cmd == "close")
				{
					break;
				}
			}

		}
	}
}
